package com.zhipeipt.pdf;

import cn.hutool.core.util.StrUtil;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.element.Image;
import com.itextpdf.styledxmlparser.node.IElementNode;
import com.itextpdf.styledxmlparser.resolver.font.BasicFontProvider;
import com.itextpdf.svg.converter.SvgConverter;
import com.itextpdf.svg.processors.impl.SvgConverterProperties;
import com.itextpdf.svg.renderers.ISvgNodeRenderer;
import com.itextpdf.svg.renderers.factories.DefaultSvgNodeRendererFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public interface SvgUtil {

    static Image convert(String svg, PdfDocument document) throws IOException {
        SvgConverterProperties properties = new SvgConverterProperties();
        PdfFont font = document.getDefaultFont();
        BasicFontProvider basicFontProvider = new BasicFontProvider(false, false, font.getFontProgram().getFontNames().toString());
        basicFontProvider.addFont(font.getFontProgram());
        properties.setFontProvider(basicFontProvider);
        properties.setRendererFactory(new DefaultSvgNodeRendererFactory() {
            @Override
            public ISvgNodeRenderer createSvgNodeRendererForTag(IElementNode tag, ISvgNodeRenderer parent) {
                return super.createSvgNodeRendererForTag(tag, parent);
            }

            @Override
            public boolean isTagIgnored(IElementNode tag) {
                if (StrUtil.equalsIgnoreCase(tag.name(), "textPath")){
                    return true;
                }
                return super.isTagIgnored(tag);
            }
        });
        return SvgConverter.convertToImage(new ByteArrayInputStream(svg.replaceAll("textPath", "tspan").getBytes(StandardCharsets.UTF_8)), document, properties);
    }

}
